/**
 * @file bsp_mpu6050_handler.c
 * @author liufeng (liufeng@injoinic.com)
 * @brief mpu6050 handler
 * @version 0.1
 * @date 2024-12-01
 *
 * @copyright Copyright (c) 2024  injoinic
 *
 */

// clang-format off
#include "bsp_mpu6050_handler.h"
#include "bsp_mpu6050_driver.h"
#include "main.h"
#include "hal_iic.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
// clang-format on

mpu6050_driver_typedef mpu6050_instance;

void mpu6050HandlerTask(void* argument)
{
    void* task_to_notify = xTaskGetCurrentTaskHandle();
    mpu6050_construct(&mpu6050_instance, &i2c1_handle, task_to_notify);
    mpu6050_instance.pf_init(&mpu6050_instance);

    while (1) {
        // 等待dma中断发送任务通知
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        // 发送待处理的缓冲区地址到消息队列
        uint8_t* read_addr =
            mpu6050_instance.mpu6050_data_buff.pf_read_addr(&mpu6050_instance.mpu6050_data_buff
            );
        xQueueSend(mpu6050_instance.unpack_queue, &read_addr, portMAX_DELAY);
    }
}

void DMA1_Stream0_IRQHandler(void)
{
    if (LL_DMA_IsEnabledIT_TC(i2c1_handle.dmarx, i2c1_handle.dmarx_stream) &&
        LL_DMA_IsActiveFlag_TC0(i2c1_handle.dmarx)) {
        LL_DMA_ClearFlag_TC0(i2c1_handle.dmarx);

        LL_I2C_DisableDMAReq_RX(i2c1_handle.Instance);
        LL_I2C_GenerateStopCondition(i2c1_handle.Instance);

        mpu6050_instance.pfdma_completed_callback(&mpu6050_instance);
    }
}

void EXTI9_5_IRQHandler(void)
{
    if (LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_8) != RESET) {
        LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_8);

        mpu6050_instance.pfint_interrupt_callback(&mpu6050_instance);
    }
}
